package com.example.stockholdtrack

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.stockholdtrack.data.PositionRecord
import com.example.stockholdtrack.data.StockDataStore
import com.example.stockholdtrack.ui.StockDetailViewModel
import com.example.stockholdtrack.ui.theme.StockHoldTrackTheme
import java.text.SimpleDateFormat
import java.util.Locale

class StockDetailActivity : ComponentActivity() {
    private var viewModel: StockDetailViewModel? = null
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        println("DEBUG: StockDetailActivity.onCreate - 详情页面创建")
        enableEdgeToEdge()
        
        val stockCode = intent.getStringExtra("stock_code") ?: ""
        val dataStore = StockDataStore(this)
        
        setContent {
            StockHoldTrackTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    StockDetailScreen(
                        stockCode = stockCode,
                        dataStore = dataStore,
                        onBackClick = { 
                            setResult(android.app.Activity.RESULT_OK)
                            finish() 
                        },
                        modifier = Modifier.padding(innerPadding),
                        onViewModelCreated = { vm ->
                            viewModel = vm
                            vm.requestStockPrice()
                        }
                    )
                }
            }
        }
    }
    
    override fun onResume() {
        super.onResume()
        println("DEBUG: StockDetailActivity.onResume - 页面恢复，重新计算数据并请求股价")
        viewModel?.let { vm ->
            // 重新计算股票数据
            vm.recalculateStockData()
            vm.requestStockPrice()
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()
        println("DEBUG: StockDetailActivity.onDestroy - 页面销毁")
    }
}

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun StockDetailScreen(
    stockCode: String,
    dataStore: StockDataStore,
    onBackClick: () -> Unit,
    modifier: Modifier = Modifier,
    onViewModelCreated: (StockDetailViewModel) -> Unit = {}
) {
    var showAddPositionDialog by remember { mutableStateOf(false) }
    var showEditPositionDialog by remember { mutableStateOf(false) }
    var selectedRecord by remember { mutableStateOf<PositionRecord?>(null) }
    
    val viewModel: StockDetailViewModel = viewModel(
        factory = StockDetailViewModel.Factory(dataStore, stockCode)
    )
    
    LaunchedEffect(viewModel) {
        onViewModelCreated(viewModel)
    }
    
    val stock by viewModel.stock.collectAsStateWithLifecycle()
    val positionRecords by viewModel.positionRecords.collectAsStateWithLifecycle()
    val isLoading by viewModel.isLoading.collectAsStateWithLifecycle()
    
    var isRefreshing by remember { mutableStateOf(false) }
    val pullRefreshState = rememberPullRefreshState(
        refreshing = isRefreshing,
        onRefresh = {
            println("DEBUG: StockDetailActivity.pullRefreshState - 触发下拉刷新")
            isRefreshing = true
            viewModel.requestStockPrice()
        }
    )
    
    // 监听加载状态变化，结束下拉刷新
    LaunchedEffect(isLoading) {
        if (!isLoading && isRefreshing) {
            println("DEBUG: StockDetailActivity.LaunchedEffect - 加载完成，结束下拉刷新")
            isRefreshing = false
        }
    }
    
    // 新增：专门监听下拉刷新状态，确保在股价请求完成后重置
    LaunchedEffect(stock, isLoading) {
        if (isRefreshing && !isLoading) {
            println("DEBUG: StockDetailActivity.LaunchedEffect - 股价请求完成，重置下拉刷新状态")
            isRefreshing = false
        }
    }
    
    Column(modifier = modifier.fillMaxSize()) {
        // 顶部标题栏
        Surface(
            modifier = Modifier.fillMaxWidth(),
            color = Color(0xFFE53935),
            shadowElevation = 4.dp
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                IconButton(onClick = { 
                    println("DEBUG: StockDetailActivity - 返回按钮被点击")
                    onBackClick() 
                }) {
                    Icon(
                        imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                        contentDescription = "返回",
                        tint = Color.White
                    )
                }
                
                Spacer(modifier = Modifier.width(8.dp))
                
                Column(
                    modifier = Modifier.weight(1f),
                    verticalArrangement = Arrangement.spacedBy(2.dp)
                ) {
                    Text(
                        text = stock?.name ?: "",
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color.White
                    )
                    Text(
                        text = stock?.code ?: "",
                        fontSize = 14.sp,
                        color = Color.White.copy(alpha = 0.8f)
                    )
                }
            }
        }
        
        // 详情内容
        if (isLoading && !isRefreshing) {
            Box(
                modifier = Modifier.weight(1f),
                contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator()
            }
        } else {
            Box(
                modifier = Modifier
                    .weight(1f)
                    .pullRefresh(pullRefreshState)
            ) {
                LazyColumn(
                    contentPadding = PaddingValues(12.dp),
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    item {
                        // 仓位信息卡片
                        Card(
                            modifier = Modifier.fillMaxWidth(),
                            shape = RoundedCornerShape(12.dp),
                            elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
                        ) {
                            Column(
                                modifier = Modifier.padding(16.dp),
                                verticalArrangement = Arrangement.spacedBy(8.dp)
                            ) {
                                Text(
                                    text = "仓位信息",
                                    fontSize = 16.sp,
                                    fontWeight = FontWeight.Bold,
                                    color = Color.Black
                                )
                                
                                Row(
                                    modifier = Modifier.fillMaxWidth(),
                                    horizontalArrangement = Arrangement.SpaceBetween
                                ) {
                                    Text("仓位数量", fontSize = 14.sp, color = Color.Gray)
                                    Text(
                                        "${stock?.quantity ?: 0}股",
                                        fontSize = 16.sp,
                                        fontWeight = FontWeight.Bold,
                                        color = Color.Black
                                    )
                                }
                                
                                // 添加当前股价显示
                                Row(
                                    modifier = Modifier.fillMaxWidth(),
                                    horizontalArrangement = Arrangement.SpaceBetween
                                ) {
                                    Text("当前股价", fontSize = 14.sp, color = Color.Gray)
                                    val currentPrice = stock?.currentPrice ?: 0.0
                                    Text(
                                        if (currentPrice > 0) 
                                            "¥${String.format("%.2f", currentPrice)}"
                                        else 
                                            "暂无数据",
                                        fontSize = 16.sp,
                                        fontWeight = FontWeight.Bold,
                                        color = if (currentPrice > 0) 
                                            Color(0xFFE53935) else Color.Gray
                                    )
                                }
                                
                                Row(
                                    modifier = Modifier.fillMaxWidth(),
                                    horizontalArrangement = Arrangement.SpaceBetween
                                ) {
                                    Text("平均仓位价", fontSize = 14.sp, color = Color.Gray)
                                    Text(
                                        "¥${String.format("%.2f", stock?.averagePrice ?: 0.0)}",
                                        fontSize = 16.sp,
                                        fontWeight = FontWeight.Bold,
                                        color = Color(0xFFE53935)
                                    )
                                }
                                
                                Row(
                                    modifier = Modifier.fillMaxWidth(),
                                    horizontalArrangement = Arrangement.SpaceBetween
                                ) {
                                    Text("仓位市值", fontSize = 14.sp, color = Color.Gray)
                                    Text(
                                        "¥${String.format("%.2f", (stock?.averagePrice ?: 0.0) * (stock?.quantity ?: 0))}",
                                        fontSize = 16.sp,
                                        fontWeight = FontWeight.Bold,
                                        color = Color(0xFFE53935)
                                    )
                                }
                            }
                        }
                    }
                    
                    item {
                        Text(
                            text = "仓位记录",
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Bold,
                            color = Color.Black,
                            modifier = Modifier.padding(vertical = 4.dp)
                        )
                    }
                    
                    if (positionRecords.isNotEmpty()) {
                        items(positionRecords, key = { it.id }) { record ->
                            PositionRecordItem(
                                record = record,
                                onClick = {
                                    selectedRecord = record
                                    showEditPositionDialog = true
                                },
                                index = positionRecords.indexOf(record)
                            )
                        }
                    }
                }
                
                PullRefreshIndicator(
                    refreshing = isRefreshing,
                    state = pullRefreshState,
                    modifier = Modifier.align(Alignment.TopCenter),
                    backgroundColor = Color.White,
                    contentColor = Color(0xFFE53935)
                )
            }
        }
        
        // 底部新建按钮
        Surface(
            modifier = Modifier.fillMaxWidth(),
            color = Color.White,
            shadowElevation = 8.dp
        ) {
            Button(
                onClick = { showAddPositionDialog = true },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(12.dp),
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color(0xFFE53935)
                ),
                shape = RoundedCornerShape(8.dp)
            ) {
                Text(
                    text = "新建仓位",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color.White
                )
            }
        }
    }
    
    // 新建仓位弹窗
    if (showAddPositionDialog) {
        AddPositionDialog(
            onDismiss = { showAddPositionDialog = false },
            onConfirm = { quantity, price ->
                val newRecord = PositionRecord(
                    quantity = quantity,
                    price = price
                )
                viewModel.addPositionRecord(newRecord)
                showAddPositionDialog = false
            }
        )
    }
    
    // 编辑仓位记录弹窗
    if (showEditPositionDialog && selectedRecord != null) {
        EditPositionDialog(
            record = selectedRecord!!,
            onDismiss = { 
                showEditPositionDialog = false
                selectedRecord = null
            },
            onConfirm = { newQuantity: Int, newPrice: Double ->
                val updatedRecord = selectedRecord!!.copy(
                    quantity = newQuantity,
                    price = newPrice
                )
                viewModel.updatePositionRecord(updatedRecord)
                showEditPositionDialog = false
                selectedRecord = null
            },
            onDelete = {
                viewModel.deletePositionRecord(selectedRecord!!)
                showEditPositionDialog = false
                selectedRecord = null
            }
        )
    }
}

@Composable
fun PositionRecordItem(
    record: PositionRecord,
    onClick: () -> Unit,
    index: Int = -1
) {
    val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
    
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 2.dp)
            .pointerInput(Unit) {
                detectTapGestures(
                    onLongPress = { onClick() }
                )
            },
        shape = RoundedCornerShape(8.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(12.dp)
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Column(
                    modifier = Modifier.weight(1f),
                    verticalArrangement = Arrangement.spacedBy(2.dp)
                ) {
                    Text(
                        text = "仓位: ${record.quantity}股",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color.Black
                    )
                    Text(
                        text = "建仓价格: ¥${record.price}",
                        fontSize = 14.sp,
                        color = Color.Gray
                    )
                    Text(
                        text = dateFormat.format(record.date),
                        fontSize = 12.sp,
                        color = Color.Gray
                    )
                }
                
                Column(
                    horizontalAlignment = Alignment.End,
                    verticalArrangement = Arrangement.spacedBy(2.dp)
                ) {
                    Text(
                        text = "¥${record.price * record.quantity}",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFFE53935)
                    )
                    Text(
                        text = "仓位价值",
                        fontSize = 12.sp,
                        color = Color.Gray
                    )
                }
            }
        }
    }
}

@Composable
fun AddPositionDialog(
    onDismiss: () -> Unit,
    onConfirm: (Int, Double) -> Unit
) {
    var quantity by remember { mutableStateOf("") }
    var price by remember { mutableStateOf("") }
    
    Dialog(onDismissRequest = onDismiss) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            shape = RoundedCornerShape(16.dp),
            elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
        ) {
            Column(
                modifier = Modifier.padding(24.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                Text(
                    text = "新建仓位",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.onSurface
                )
                
                OutlinedTextField(
                    value = price,
                    onValueChange = { price = it },
                    label = { Text("建仓价格") },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal)
                )
                
                OutlinedTextField(
                    value = quantity,
                    onValueChange = { quantity = it },
                    label = { Text("仓位数量") },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
                )
                
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    OutlinedButton(
                        onClick = onDismiss,
                        modifier = Modifier.weight(1f)
                    ) {
                        Text("取消")
                    }
                    
                    Button(
                        onClick = { 
                            val quantityInt = quantity.toIntOrNull() ?: 0
                            val priceDouble = price.toDoubleOrNull() ?: 0.0
                            if (quantityInt > 0 && priceDouble > 0) {
                                onConfirm(quantityInt, priceDouble)
                            }
                        },
                        modifier = Modifier.weight(1f),
                        enabled = quantity.isNotBlank() && price.isNotBlank() && 
                                quantity.toIntOrNull() != null && price.toDoubleOrNull() != null &&
                                quantity.toIntOrNull()!! > 0 && price.toDoubleOrNull()!! > 0
                    ) {
                        Text("确认")
                    }
                }
            }
        }
    }
}

@Composable
fun EditPositionDialog(
    record: PositionRecord,
    onDismiss: () -> Unit,
    onConfirm: (Int, Double) -> Unit,
    onDelete: () -> Unit
) {
    var quantity by remember { mutableStateOf("") }
    var price by remember { mutableStateOf("") }
    
    LaunchedEffect(record.id) {
        quantity = record.quantity.toString()
        price = record.price.toString()
    }
    
    Dialog(onDismissRequest = onDismiss) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            shape = RoundedCornerShape(16.dp),
            elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
        ) {
            Column(
                modifier = Modifier.padding(24.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "编辑仓位记录",
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.onSurface
                    )
                    
                    Button(
                        onClick = onDelete,
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(0xFFD32F2F)
                        ),
                        shape = RoundedCornerShape(8.dp)
                    ) {
                        Text("删除", fontSize = 12.sp)
                    }
                }
                
                OutlinedTextField(
                    value = price,
                    onValueChange = { price = it },
                    label = { Text("建仓价格") },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal)
                )
                
                OutlinedTextField(
                    value = quantity,
                    onValueChange = { quantity = it },
                    label = { Text("仓位数量") },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
                )
                
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    OutlinedButton(
                        onClick = onDismiss,
                        modifier = Modifier.weight(1f)
                    ) {
                        Text("取消")
                    }
                    
                    Button(
                        onClick = { 
                            val quantityInt = quantity.toIntOrNull() ?: 0
                            val priceDouble = price.toDoubleOrNull() ?: 0.0
                            if (quantityInt > 0 && priceDouble > 0) {
                                onConfirm(quantityInt, priceDouble)
                            }
                        },
                        modifier = Modifier.weight(1f),
                        enabled = quantity.isNotBlank() && price.isNotBlank() && 
                                quantity.toIntOrNull() != null && price.toDoubleOrNull() != null &&
                                quantity.toIntOrNull()!! > 0 && price.toDoubleOrNull()!! > 0
                    ) {
                        Text("确认")
                    }
                }
            }
        }
    }
} 